/*
 * StateAwareVCR.java
 *
 * Created on December 1, 2005, 4:17 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.mbari.vcr;

import java.util.Timer;
import java.util.TimerTask;

/**
 * This class is a replacement fo the SonyVCRProxy. It is greatly simplified and
 * does much more. It monitors timecode as well as state automatically. In record
 * mode it also writes timecode to the userbits on the tape.
 *
 * @author brian
 */
public class TimecodeMonitoringVCR extends MonitoringVCR {
    
    /**
	 * @uml.property  name="stopObserver"
	 * @uml.associationEnd  multiplicity="(1 1)" inverse="this$0:org.mbari.vcr.TimecodeMonitoringVCR$StopObserver"
	 */
    private final StopObserver stopObserver = new StopObserver();
    
    /**
     * Creates a new instance of StateMonitoringVCR
     */
    public TimecodeMonitoringVCR() {
        this(new VCRAdapter());
    }
    
    public TimecodeMonitoringVCR(IVCR vcr) {
        addStateObserver(stopObserver);
        setVcr(vcr);
    }

    /**
     * This class listens to the state of the VCR. If it is stopped it stops
     * the requests for timecodes to the VCR. When the VCR tape is in motion
     * it sends requests for updated timecodes.
     */
    private class StopObserver extends StateObserver {
        
        
        
        StopObserver() {
            super();
            intervalMin = 33;
            long INTERVAL_DEFAULT = 500;
            setInterval(INTERVAL_DEFAULT);
        }
        
        
        void startTimer() {
            if (getTimer() == null) {
                setTimer(new Timer(true));
                getTimer().schedule(new ReadTimecodeTimerTask(), 0, getInterval());
            }
        }
        
        /**
         * This is used to monitor the timecode during VCR operations
         */
        private class ReadTimecodeTimerTask extends TimerTask {
            public void run() {
                /*
                 * LTimeCode is on the audio track. It's slightly less accurate than
                 * the VTimeCode, however, the VTimeCode can't be read except when
                 * the VCR is playing. So use the LTimeCode for everything but
                 * play mode.
                 */
                if (getVcrState().isPlaying()) {
                    requestVTimeCode();
                } else {
                    requestLTimeCode();
                }
            }
        }
    }
    
   
    
}
